﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;
using LERP.Domain;
using LERP.Domain.Enums;
using Sharp.Framework.Extensions;
using Sharp.Framework.Queries;
using SharpArch.NHibernate.Web.Mvc;

namespace LERP.Web.Controllers
{
    public class SubsidiaryController : Controller
    {

        private readonly IQuery _query;

        public SubsidiaryController(IQuery query)
        {
            _query = query;
        }

        /// <summary>
        /// 签约公司
        /// </summary> 
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index()
        {

            var query = _query.FindAll<Subsidiary>().Where(x => x.Status == DataStatus.Normal);


            var model = query.OrderByDescending(m => m.Modified).Select(x => new SubsidiaryViewModels
                                                                                 {
                                                                                     Created = x.Created,
                                                                                     Id = x.Id,
                                                                                     Name = x.Name
                                                                                 }).ToList();

            return View(model);
        }



        /// <summary>
        /// 签约公司
        /// </summary>
        /// <param name="idd"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost]
        [Transaction]
        public ActionResult Index(int? idd, string name)
        {
            var entity = new Subsidiary {Created = DateTime.Now};
            if (idd.HasValue)
            {
                entity = _query.Get<Subsidiary>(idd.Value);
                if (null == entity)
                {
                    return View("NoFound");
                }
            }
            entity.Name = name;
            entity.Modified = DateTime.Now;
            _query.Save(entity);
            return Redirect(Url.Action("Index","Subsidiary"));
        }

        [Transaction]
        [HttpGet]
        public ActionResult Delete(int id, string returnUrl)
        {
            var entity = _query.Get<Subsidiary>(id);

            if (null == entity)
            {
                return View("NoFound");
            }
            entity.Status = DataStatus.Deleted;
            _query.Save(entity);
            return RedirectToAction("Index");
        }

    }

    public class SubsidiaryViewModels
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public DateTime Created { get; set; }
    }
}
